package control;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;
import util.Copy;

import com.oreilly.servlet.MultipartRequest;
import com.sun.xml.internal.bind.v2.runtime.output.Encoded;

import dao.UserData;

/**
 * Servlet implementation class Register
 */
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8");
		
		String avatarFolder = getServletContext().getRealPath("temp");
		String goc = getServletContext().getRealPath("image\\avatarImage");
		MultipartRequest mtr = new MultipartRequest(request, avatarFolder, 5*1024*1024,"UTF-8");
		UserData User = new UserData();
		String email = mtr.getParameter("email");
		String password = mtr.getParameter("password"); 
		String re_password = mtr.getParameter("re_password");
		String name = mtr.getParameter("name"); 
		String sex = mtr.getParameter("sex"); 
		String date = mtr.getParameter("date");
		String phone = mtr.getParameter("phone"); 
		boolean checkEmail =User.checkEmail(email);
		String password_err = "";
		if (mtr.getFile("avatar") != null) {
			System.out.println(goc + "\\" + email + ".png");
			System.out.println(goc + "\\" + email + ".png");
			Copy.copy(avatarFolder+mtr.getFile("avatar").getName(),goc + "\\" + email + ".png");
		}
		
		
		String email_err = "";
		email = email.trim();
		if (email.equals("")) {
			email_err += "bạn chưa nhập email";
		} else {
		Pattern patternObject = Pattern .compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"); 
		Matcher matcherObject = patternObject.matcher(email);
		if (!matcherObject.matches()) {
			email_err += "bạn nhập email không hợp lệ";
		} else {
			if(checkEmail){
					email_err += "địa chia email đã có người sử dụng";
			}
				}
			}
		re_password = re_password.trim();
		if (password.equals("")){
			password_err = "Bạn chưa nhập mật khẩu";
		}
		
		password = password.trim();
		re_password = re_password.trim();
		if (password.equals("")){
			password_err = "Bạn chưa nhập mật khẩu";
		}
		else if (!password.equals(re_password)){
			password_err = "Hai Mật khẩu không giống nhau";
		}
		//bat loi cho name
		
		String name_err = "";
		if (name.equals("")) {
			name_err = "Bạn chưa nhập tên";
		}
		//bat loi cho phone
		
		String phone_err = "";
		if (phone.equals("")) {
			phone_err = "Bạn chưa nhập số điện thoại";
		}
		else {
			Pattern patternObject = Pattern .compile("^[_0-9-\\+]+(\\.[0-9-])*$"); 
			Matcher matcherObject = patternObject.matcher(phone);
			if (!matcherObject.matches()) {
				phone_err += "số dien thoại nhập không hợp lệ";
			}
		}
		
		//bat loi cho ngay sinh
		
		String url = "/congratulationReg.jsp";
		String encoded = util.Encoded.getSHA1(password);
		User user = new User(email, encoded, name, sex, date, phone, goc + "\\" + email + ".png",0);
		if(!checkEmail && password_err.equals("") && phone_err.equals("")&& name_err.equals("")){
		User.addUser(user);
		String Folder = getServletContext().getRealPath("temp");
		Copy.copy(avatarFolder + "\\" + email + ".png", Folder+"/"+ email+".png");
		String body = "Chào Mừng bạn đến với Game Đai chiến Thiên Sơn "+ "\r\n"+"" +
				"Bạn Vừa Đăng ký thành công tài khoản tại trang game thiên Sơn," +
				"bây giờ bạn cần click vào đường link dưới đây dể sác nhận";
	     util.Util u = new util.Util();
//	      try {
//			u.sendMail(email);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		}
		request.setAttribute("email", email);
		request.setAttribute("name", name);
		request.setAttribute("phone", phone);
		if (email_err.length() > 0 || password_err.length() > 0 || name_err.length() > 0 || phone_err.length() > 0 ) {
			url = "/Regis.jsp";
			request.setAttribute("email_err", email_err);
			request.setAttribute("password_err", password_err);
			request.setAttribute("name_err", name_err);
			request.setAttribute("phone_err", phone_err);
		}
		RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
		rd.forward(request, response);
		
	}
	}


